package com.hjm.friend.manage;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hjm.common.core.constants.CacheConstants;
import com.hjm.friend.domain.user.User;
import com.hjm.friend.mapper.user.UserMapper;
import com.hjm.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long userId) {
        User user = redisService.getCacheMapValue(getCacheUserKey(), String.valueOf(userId), User.class);
        if (user == null) {
            user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .select(User::getUserId,
                            User::getNickName,
                            User::getHeadImage,
                            User::getSex,
                            User::getEmail,
                            User::getPhone,
                            User::getWechat,
                            User::getIntroduce,
                            User::getSchoolName,
                            User::getStatus,
                            User::getMajorName)
                    .eq(User::getUserId, userId));
            refreshUser(user);
        }
        return user;
    }

    public void refreshUser(User user) {
        //刷新用户缓存
        redisService.setCacheMapValue(getCacheUserKey(), String.valueOf(user.getUserId()), user);
        //设置用户缓存有效期为一年
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
        redisService.expire(getCacheUserKey(), seconds, TimeUnit.SECONDS);
    }

    private String getCacheUserKey() {
        return CacheConstants.USER_KEY;
    }
}


